package client.user;

import client.common.dto.AdminRegisterReqDTO;
import client.common.result.Result;
import client.common.vo.RoleVO;
import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;
import remote.service.RoleService;
import remote.service.UserService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.function.Consumer;

public class UserAddDialog extends JDialog {
    private JDatePickerImpl birthDatePicker;
    private JRadioButton maleRadio;
    private JRadioButton femaleRadio;
    private JTextField phoneField;
    private JTextField addressField;
    private JTextField idCardField;
    private JTextField nameField;
    private JPasswordField passwordField;
    private JComboBox<String> roleComboBox;  // 角色选择框
    private JButton registerButton;
    private JButton backButton;
    private UserService userService = new UserService() {
    };  // 实例化 UserService 对象
    private RoleService roleService = new RoleService() {
    };  // 实例化 RoleService 对象
    private Consumer<Result> refreshCallback;
    private List<RoleVO> roles;  // 角色列表
    
    public UserAddDialog(Consumer<Result> refreshCallback) {
        this.refreshCallback = refreshCallback;
        setTitle("新增用户信息");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        
        // 背景色设置
        getContentPane().setBackground(Color.decode("#F0F8FF"));
        
        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 16);
        Font textFieldFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        // 名字输入
        nameField = createTextField();
        addComponent(gbc, 0, 0, "姓名:", labelFont);
        addComponent(gbc, 1, 0, nameField, textFieldFont);
        
        // 密码输入
        passwordField = new JPasswordField();
        passwordField.setFont(textFieldFont);
        passwordField.setPreferredSize(new Dimension(250, 30));
        addComponent(gbc, 0, 1, "密码:", labelFont);
        addComponent(gbc, 1, 1, passwordField, textFieldFont);
        
        // 性别选择
        maleRadio = new JRadioButton("男", true);
        femaleRadio = new JRadioButton("女");
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(maleRadio);
        genderGroup.add(femaleRadio);
        JPanel genderPanel = new JPanel();
        genderPanel.setBackground(Color.decode("#F0F8FF"));
        genderPanel.add(maleRadio);
        genderPanel.add(femaleRadio);
        addComponent(gbc, 0, 2, "性别:", labelFont);
        gbc.gridx = 1;
        gbc.gridy = 2;
        add(genderPanel, gbc);
        
        // 出生日期选择
        addComponent(gbc, 0, 3, "出生日期:", labelFont);
        gbc.gridx = 1;
        gbc.gridy = 3;
        birthDatePicker = createDatePicker();
        add(birthDatePicker, gbc);
        
        // 电话号码输入
        phoneField = createTextField();
        addComponent(gbc, 0, 4, "电话号码:", labelFont);
        addComponent(gbc, 1, 4, phoneField, textFieldFont);
        
        // 身份证号输入
        idCardField = createTextField();
        addComponent(gbc, 0, 5, "身份证号:", labelFont);
        addComponent(gbc, 1, 5, idCardField, textFieldFont);
        
        // 住址输入
        addressField = createTextField();
        addComponent(gbc, 0, 6, "住址:", labelFont);
        addComponent(gbc, 1, 6, addressField, textFieldFont);
        
        // 角色选择框
        roleComboBox = new JComboBox<>();
        addComponent(gbc, 0, 7, "角色类型:", labelFont);
        gbc.gridx = 1;
        gbc.gridy = 7;
        add(roleComboBox, gbc);
        loadRolesIntoComboBox();  // 加载角色数据
        
        // 创建用户按钮
        registerButton = new JButton("创建用户");
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        registerButton.setBackground(Color.decode("#4CAF50"));
        registerButton.setForeground(Color.WHITE);
        registerButton.setFocusPainted(false);
        gbc.gridx = 0;
        gbc.gridy = 8;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(registerButton, gbc);
        
        // 返回按钮
        backButton = new JButton("返回选择界面");
        backButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        backButton.setBackground(Color.decode("#F44336"));
        backButton.setForeground(Color.WHITE);
        backButton.setFocusPainted(false);
        gbc.gridy = 9;
        add(backButton, gbc);
        
        // 注册按钮事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleRegisterButtonClick();
            }
        });
        
        // 返回按钮事件
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        
        setLocationRelativeTo(null);
        setVisible(true);
        revalidate();
        repaint();
    }
    
    private JTextField createTextField() {
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(250, 30));
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        return textField;
    }
    
    private void addComponent(GridBagConstraints gbc, int x, int y, String label, Font font) {
        gbc.gridx = x;
        gbc.gridy = y;
        JLabel jLabel = new JLabel(label);
        jLabel.setFont(font);
        add(jLabel, gbc);
    }
    
    private void addComponent(GridBagConstraints gbc, int x, int y, JComponent component, Font font) {
        gbc.gridx = x;
        gbc.gridy = y;
        component.setFont(font);
        add(component, gbc);
    }
    
    private JDatePickerImpl createDatePicker() {
        UtilDateModel model = new UtilDateModel();
        model.setSelected(true);
        Properties p = new Properties();
        p.put("text.today", "Today");
        p.put("text.month", "Month");
        p.put("text.year", "Year");
        JDatePanelImpl datePanel = new JDatePanelImpl(model, p);
        JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
        datePicker.setPreferredSize(new Dimension(250, 30));
        return datePicker;
    }
    
    private void loadRolesIntoComboBox() {
        Result<List<RoleVO>> roleResult = roleService.getRoleList();
        if (roleResult.isSuccess() && roleResult.getData() != null) {
            roles = roleResult.getData();
            for (RoleVO role : roles) {
                roleComboBox.addItem(role.getName());
            }
        } else {
            JOptionPane.showMessageDialog(this, "加载角色失败：" + roleResult.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void handleRegisterButtonClick() {
        try {
            // 校验姓名
            if (nameField.getText().trim().isEmpty() || !nameField.getText().matches("^[\\u4e00-\\u9fa5]+$")) {
                JOptionPane.showMessageDialog(this, "姓名必须为汉字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验密码
            String password = new String(passwordField.getPassword());
            if (password.trim().isEmpty() || !password.matches("^\\d+$")) {
                JOptionPane.showMessageDialog(this, "密码必须为数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验性别
            if (!maleRadio.isSelected() && !femaleRadio.isSelected()) {
                JOptionPane.showMessageDialog(this, "请选择性别", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 获取出生日期
            Date selectedDate = (Date) birthDatePicker.getModel().getValue();
            if (selectedDate == null) {
                JOptionPane.showMessageDialog(this, "请选择出生日期", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验电话号码
            if (phoneField.getText().trim().isEmpty() || !phoneField.getText().matches("^\\d{11}$")) {
                JOptionPane.showMessageDialog(this, "电话号码必须为11位数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验身份证号
            if (idCardField.getText().trim().isEmpty() || !idCardField.getText().matches("^\\d{17}([0-9]|X)$")) {
                JOptionPane.showMessageDialog(this, "身份证号必须为18位数字，最后一位可以是数字或X", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验角色
            String selectedRoleName = (String) roleComboBox.getSelectedItem();
            RoleVO selectedRole = roles.stream()
                    .filter(role -> role.getName().equals(selectedRoleName))
                    .findFirst()
                    .orElse(null);
            
            if (selectedRole == null) {
                JOptionPane.showMessageDialog(this, "请选择角色", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验通过后，构建 DTO 对象
            AdminRegisterReqDTO requestDTO = new AdminRegisterReqDTO();
            requestDTO.setRealName(nameField.getText());
            requestDTO.setPassword(password);
            requestDTO.setGender(maleRadio.isSelected() ? "男" : "女");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            requestDTO.setBirth(sdf.format(selectedDate));
            requestDTO.setPhoneNumber(phoneField.getText());
            requestDTO.setIdentity(idCardField.getText());
            
            // 地址可以为空
            requestDTO.setAddress(addressField.getText());
            requestDTO.setRoleId(selectedRole.getId());
            
            // 调用服务创建用户
            Result<String> result = userService.addUser(requestDTO);
            JOptionPane.showMessageDialog(this, result.getMessage());
            if (result.isSuccess()) {
                this.dispose();
                if (refreshCallback != null) {
                    refreshCallback.accept(result);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "用户创建失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 日期格式化器
    public class DateLabelFormatter extends JFormattedTextField.AbstractFormatter {
        private String datePattern = "yyyy-MM-dd";
        private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
        
        @Override
        public Object stringToValue(String text) throws java.text.ParseException {
            return dateFormatter.parseObject(text);
        }
        
        @Override
        public String valueToString(Object value) throws java.text.ParseException {
            if (value != null) {
                Calendar cal = (Calendar) value;
                return dateFormatter.format(cal.getTime());
            }
            return "";
        }
    }
    
    
}
